﻿using Kingdee.BOS.App;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;


namespace K.KDL
{
    [Description("收料单：获取进货批号")]
    [HotUpdate]
    public class CustomPrurReceiveFormPlugin : AbstractDynamicFormPlugIn
    {
        //FormMetadata _arMeta;

        public override void AfterEntryBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterEntryBarItemClick(e);

            if (e.BarItemKey == "PATC_updateJHPH")
            {
                RefreshLotInfo();
            }
        }

        void RefreshLotInfo()
        {
            var entity = this.View.Model.DataObject;
            var lines = entity["PUR_ReceiveEntry"] as DynamicObjectCollection;
            if (lines == null || lines.Count() == 0)
            {
                return;
            }

            var id = Convert.ToInt32(entity["Id"]);
            var date = (DateTime)entity["Date"];
            var supplierId = Convert.ToInt32(entity["SupplierId_Id"]);
            if (supplierId <= 0) return;
            var suppplier = entity["SupplierId"] as DynamicObject;

            var sql2 = @"/*dialect*/select FSHORTNAME
                                from T_BD_SUPPLIER_L
                                where FSUPPLIERID={0} and FLOCALEID=2052";
            var shotName = DBUtils.ExecuteDynamicObject(Context, string.Format(sql2, supplierId)).First();
            var tempShotName = "";
            if (shotName != null && shotName["FSHORTNAME"] != null)
            {
                tempShotName = shotName["FSHORTNAME"].ToString();
            }

            var from = new DateTime(date.Year, date.Month, 1);
            var sql = @"/*dialect*/SELECT COUNT(1) AS CNT
                            FROM T_PUR_Receive
                            WHERE FDATE>='{0}' {1} {2}";  //AND FSUPPLIERID='{1}' {2}
            var row = DBUtils.ExecuteDynamicObject(Context, string.Format(sql, from, shotName.IsNullOrEmpty() ? string.Empty : String.Format(" AND FSUPPLIERID='{0}'", supplierId), id <= 0 ? string.Empty : $"AND FID<'{id}'")).First();
            var seq = Convert.ToInt32(row[0]) + 1;

            var lotNumber = $"{tempShotName}{date.ToString("yyMM")}{seq.ToString().PadLeft(3, '0')}";
            for (int i = 0; i < lines.Count; i++)
            {
                var line = lines[i];
                this.View.BusinessInfo.GetField("F_PATC_JHPH")?.DynamicProperty.SetValue(line, lotNumber); //F_QATC_LHPH               
                this.View.InvokeFieldUpdateService("F_PATC_JHPH", i);
            }

            this.View.UpdateView("F_PATC_JHPH");
            this.View.UpdateView("FDetailEntity");
        }
    }
}
